package com.hancher.common.net.interceptor;

import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.androidutil.MmkvUtil;
import com.hancher.common.javautil.EmptyUtil;
import com.hancher.common.javautil.GsonUtil;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.HashMap;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 作者 : Hancher ytu_shaoweijie@163.com <br/>
 * 时间 : 2021/2/4 9:13 <br/>
 * 描述 : response.body() 只能被调用一侧 , 所以重新创建一个 response
 */
public class JumpInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {

        try {
            Request request = chain.request();
            Request request2 = request.newBuilder().build();
            Response response = chain.proceed(request);
            String location = response.header("Location");
            if (EmptyUtil.isNotEmpty(location)) {
                Headers header3 = response.headers();
                HashMap<String, String> map = new HashMap<>();
                for (int i = 0, count = header3.size(); i < count; i++) {
                    map.put(header3.name(i), header3.get(header3.name(i)));
                }
                MmkvUtil.put("jump_302", location);
                MmkvUtil.put("jump_302_header", GsonUtil.obj2JsonStr(map));
            }
            return response;
        } catch (SocketTimeoutException se) {
            LogUtil.e("超时:" + se.getMessage());
            throw se;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

}
